import React, { PureComponent } from 'react';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col } from 'antd';
import { SecondHeaderC, ThreeHeaderC, XYAxisChartsC, FormGroup, DATA_ENTRY, PrimaryC, ComplexDateC, SelectC } from '../../../../comps';
import CardC from '../comps/cardC';
import style from './index.less';
import bg from '../../../../assets/busi/workStation/Barra/marketAnalysis_bg.png';

@connect(({ loading, marketAnalysisM }) => ({
  loading,
  marketAnalysisM,
}))
export default class MarketAnalysis extends PureComponent {
  state = {
    styleFactorYield: {}, // 风格因子收益率
    industryFactorYield: {}, // 行业因子收益率
    styleFactorRisk: {}, // 风格因子风险
    industryFactorRisk: {}, // 行业因子风险
    styleName: undefined,
    styleYield: undefined,
    industryName: undefined,
    industryYield: undefined,
  };
  componentDidMount() {
    this.setState(
      {
        status: ['11', '12', '13', '14', '1', '3'].includes(this.props.state) ? false : true,
      },
      () => {
        this.state.COMPLEXDATE.setSelctAndDate('7', moment().subtract(1, 'y'), moment());
      },
    );
    this.searchChartsData(this.props.productCode);
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.state != this.props.state) {
      this.setState({
        status: ['11', '12', '13', '14', '1', '3'].includes(nextProps.state) ? false : true,
      });
    }
    // if (nextProps.productCode != this.props.productCode) {
    // 	this.searchChartsData(nextProps.productCode)
    // }
  }

  stateOnChange = () => {
    this.setState(
      {
        status: this.state.status == 1 ? false : true,
      },
      () => {
        this.props.stateOnChange(this.state.status ? 1 : 2);
      },
    );
  };

  // echart图
  showCharts = (data, needHide) => {
    const xAxis = data && data.xAxis ? data.xAxis : [];
    const series = data && data.series ? data.series : [];
    let hideName = {};
    if (needHide && series && series.length) {
      series.map((item, index) => {
        if (index > 4) {
          hideName[item.name] = false;
        }
      });
    }
    return (
      <div style={{ height: '280px' }}>
        <XYAxisChartsC xAxis={xAxis} series={series} height='280px' yAxisUnit={['单位(%)']} dataZoom={true} width='100%' legendType='scroll' legendSelect={hideName} />
      </div>
    );
  };

  // 因子收益率
  factorYield = () => {
    const { styleFactorYield, industryFactorYield } = this.state;
    return (
      <div>
        <Row>
          <Col span={12}>
            <div style={{ marginRight: '10px' }}>
              <ThreeHeaderC title={`风格因子`} />
              {this.showCharts(styleFactorYield)}
            </div>
          </Col>
          <Col span={12}>
            <div style={{ marginLeft: '10px' }}>
              <ThreeHeaderC title='行业因子' />
              {this.showCharts(industryFactorYield, true)}
            </div>
          </Col>
        </Row>
      </div>
    );
  };

  // 因子风险
  factorRisk = () => {
    const { styleFactorRisk, industryFactorRisk } = this.state;
    return (
      <div>
        <Row>
          <Col span={12}>
            <div style={{ marginRight: '10px' }}>
              <ThreeHeaderC title={`风格因子`} />
              {this.showCharts(styleFactorRisk)}
            </div>
          </Col>
          <Col span={12}>
            <div style={{ marginLeft: '10px' }}>
              <ThreeHeaderC title='行业因子' />
              {this.showCharts(industryFactorRisk, true)}
            </div>
          </Col>
        </Row>
      </div>
    );
  };

  // 获取表单数据
  searchChartsData = (productCode) => {
    const {
      form: { validateFields },
    } = this.formGroup.props;
    const { dispatch } = this.props;
    validateFields(['beginDate', 'endDate', 'type'], (err, fieldsValue) => {
      if (err) return;
      const value = {
        // productCode: productCode,
        beginDate: fieldsValue.beginDate ? fieldsValue.beginDate.format('YYYY-MM-DD') : moment().subtract(1, 'y').add(1, 'd').format('YYYY-MM-DD'),
        endDate: fieldsValue.endDate ? fieldsValue.endDate.format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
        type: fieldsValue.type,
      };
      // 获取因子收益率数据风格因子
      dispatch({
        type: 'marketAnalysisM/getStyleFactorYield',
        payload: { ...value },
        callback: (res) => {
          this.setState({
            styleFactorYield: res,
          });
        },
      });
      // 获取因子收益率数据行业因子
      dispatch({
        type: 'marketAnalysisM/getIndustryFactorYield',
        payload: { ...value },
        callback: (res) => {
          this.setState({
            industryFactorYield: res,
          });
        },
      });
      // 获取因子风险风格因子
      dispatch({
        type: 'marketAnalysisM/getStyleFactorRisk',
        payload: { ...value },
        callback: (res) => {
          this.setState({
            styleFactorRisk: res,
          });
        },
      });
      // 获取因子风险行业因子
      dispatch({
        type: 'marketAnalysisM/getIndustryFactorRisk',
        payload: { ...value },
        callback: (res) => {
          this.setState({
            industryFactorRisk: res,
          });
        },
      });
      dispatch({
        type: 'marketAnalysisM/getMaxYield',
        payload: { ...value },
        callback: (res) => {
          this.setState({
            styleName: res.styleName,
            styleYield: res.styleYield,
            industryName: res.industryName,
            industryYield: res.industryYield,
          });
        },
      });
    });
  };

  render() {
    const { status, styleName, styleYield, industryName, industryYield } = this.state;
    const { productCode } = this.props;
    return (
      <div className={style.mainBox}>
        <div className={style.openBox} style={{ display: status ? 'block' : 'none' }}>
          {/* 展开 */}
          <CardC
            title='市场分析'
            type='3'
            showContent={status}
            onExpendClick={this.stateOnChange}
            content={
              <div className={style.boxContent}>
                <div className={style.searchBox}>
                  <div className={style.formBox}>
                    <FormGroup
                      dataSource={[
                        {
                          selectIndex: 'timeRange',
                          startIndex: 'beginDate',
                          endIndex: 'endDate',
                          title: '时间区间',
                          type: DATA_ENTRY.COMPLEXDATE,
                          selfDefination: ['0', '4', '5', '6', '7'],
                          onRef: (ref) => this.setState({ COMPLEXDATE: ref }),
                          span: 16,
                          controlLabelSpan: 6,
                        },
                        {
                          dataIndex: 'type',
                          title: '因子类型',
                          type: DATA_ENTRY.SELECT,
                          initialValue: 'barra',
                          dataSource: [{ title: 'Barra', value: 'barra' }],
                          span: 8,
                          controlLabelSpan: 6,
                        },
                      ]}
                      autoLayout={false}
                      onRef={(ref) => (this.formGroup = ref)}
                    />
                  </div>
                  <PrimaryC
                    title='查询'
                    onClick={() => {
                      this.searchChartsData();
                    }}
                  />
                </div>
                <SecondHeaderC title='因子收益率' />
                {this.factorYield()}
                <SecondHeaderC title='因子风险' topHeight={true} />
                {this.factorRisk()}
              </div>
            }
          />
        </div>
        <div className={style.closeBox} style={{ display: status ? 'none' : 'block', overflow: 'hidden' }}>
          {/* 收起 */}
          <CardC
            title='市场分析'
            type='13'
            showContent={status}
            onExpendClick={this.stateOnChange}
            content={
              <div>
                <div className={style.content}>
                  <div>
                    最近查询日风格因子中 <span className={style.num}>{styleName || '--'}</span> 收益率最高，为{' '}
                    <span className={style.num}>{styleYield ? (styleYield * 100).toFixed(2) : '--'}</span> %
                  </div>
                  <div>
                    最近查询日行业因子中 <span className={style.num}>{industryName || '--'}</span> 收益率最高，为{' '}
                    <span className={style.num}>{industryYield ? (industryYield * 100).toFixed(2) : '--'}</span> %
                  </div>
                </div>
                <div className={style.closeContbg}>
                  <img src={bg} />
                </div>
              </div>
            }
          />
        </div>
      </div>
    );
  }
}
